package com.jdls.web.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author 嘉德罗斯
 * @date 2021/9/5
 */
@WebFilter("/*")
public class LoginFilter implements Filter {
    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest) req;
        String[] url={"/css/","/imgs/","/Login.jsp","/register.jsp","/LoginServlet","/RegisterServlet","/CheckCodeServlet"};
        String requestURI = request.getRequestURI();
        for (String s : url) {
            if (requestURI.contains(s)){
                chain.doFilter(req, resp);
                return;
            }
        }
        HttpSession session = request.getSession();
        Object user = session.getAttribute("user");
        if(user!=null){
            chain.doFilter(req, resp);
        }else {
            request.setAttribute("reg","你没登陆");
            request.getRequestDispatcher("/Login.jsp").forward(request,resp);
        }
    }

    public void init(FilterConfig config) throws ServletException {

    }

}
